﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Xml.Linq;
using LinqToLfsWorld.Extensions;

namespace LinqToLfsWorld.Queries
{
	/// <summary>
	/// Queries the uploaded hotlaps on LfsWorld
	/// </summary>
	public class HotlapsQuery : LfsWorldQuery<Hotlap>
	{

		/// <summary>
		/// Initializes a new instance of the <see cref="HotlapsQuery"/> class.
		/// </summary>
		/// <param name="context">The context.</param>
		public HotlapsQuery(LfsWorldContext context)
			: base (context)
		{
		}

		/// <summary>
		/// Gets the URL used to query LfsWorld.
		/// </summary>
		/// <returns></returns>
		protected override string GetUrl()
		{
			string url = LfsHelper.GetPubstatUrlBase(PubstatResponseType.Xml, this, "hl");
			url += "&racer=" + (string)ExpressionValues["RacerName"].Value;

			return url;
		}

		/// <summary>
		/// Gets the entities given LfsWorld response XML
		/// </summary>
		/// <param name="responseData">The response data.</param>
		/// <returns>A collection of Host entities</returns>
		protected override IEnumerable<Hotlap> ProcessResponse(string responseData)
		{
			XDocument doc = XDocument.Parse(responseData);

			if (doc.Root.Name == "hl_data")
			{

				var laps = from l in doc.Descendants("entry")
						   select l;

				foreach (XElement node in laps)
				{

					Hotlap lap = new Hotlap();

					lap.RacerName = ((string)ExpressionValues["RacerName"].Value).StripLfsColours();
					lap.Id = Convert.ToInt32(node.Element("id_hl").Value);
					lap.TrackIdent = node.Element("track").Value;
					lap.TrackName = Utility.CircuitNameFactory.GetNameFromIdent(lap.TrackIdent);
					lap.Car = node.Element("car").Value;
					lap.Split1 = TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("split1").Value));
					lap.Split2 =  TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("split2").Value));
					lap.Split3 =  TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("split3").Value));
					lap.LapTime =  TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("laptime").Value));
					lap.Flags = (HotlapFlags)Convert.ToInt32(node.Element("flags_hlaps").Value);

					int ts = Convert.ToInt32(node.Element("timestamp").Value);
					lap.Timestamp = DateTimeExtensions.FromUnixTimestamp(ts);

					yield return lap;
				}
			}
		}
	}

}
